package com.example.mq2.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class MSGQueue {

    private String name;
    private boolean durable;
    private boolean exclusive;
    private boolean autoDelete;
    private Map<String, Object> arguments = new HashMap<>();
    //管理消费者
    private List<ConsumerEnv> consumerEnvs = new ArrayList<>();
    private AtomicInteger consumerIndex = new AtomicInteger(0);

    /**
     * 添加消费者
     * @param consumerEnv
     */
    public void addConsumer(ConsumerEnv consumerEnv) {
        consumerEnvs.add(consumerEnv);
    }

    /**
     * 按照轮询的方式挑选出一个消费者
     * @return
     */
    public ConsumerEnv chooseConsumer() {
        if(consumerEnvs.size() == 0) {
            //当前没有消费者
            return null;
        }
        int index = consumerIndex.get() % consumerEnvs.size();
        consumerIndex.incrementAndGet();
        ConsumerEnv consumerEnv = consumerEnvs.get(index);
        return consumerEnv;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isExclusive() {
        return exclusive;
    }

    public void setExclusive(boolean exclusive) {
        this.exclusive = exclusive;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    //以下方法提供给 SQLite
    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public void setArguments(String argumentsJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.readValue(argumentsJson, new TypeReference<Map<String, Object>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }

    public Object getArguments(String key) {
        return arguments.get(key);
    }

    public void setArguments(String key, Object value) {
        arguments.put(key, value);
    }
}
